//
//  QmAPI.swift
//  ExList
//
//  Created by qmsoft_macmini on 16/6/23.
//  Copyright © 2016年 qmsoft_macmini. All rights reserved.
//

import Foundation
import Alamofire
/**检查列表模型*/
class StudyGroupModel {
    var page:Int!
    var total:Int!
    var records:Int!
    var rows:[RowsArrayModel]!
    
    init(dic:Dictionary<String, AnyObject>) {
        self.studyGroup(dic)
    }
    
    func studyGroup(dic:Dictionary<String, AnyObject>) {
        self.page = dic["page"] as? Int ?? 0
        self.records = dic["records"] as? Int ?? 0
        self.total = dic["total"] as? Int ?? 0
        if let row = dic["rows"] as? [Dictionary<String, AnyObject>] {
            var rowAyy = [RowsArrayModel]()
            for rw in row {
                let rowsMo = RowsArrayModel(dic: rw)
                rowAyy.append(rowsMo)
            }
            self.rows = rowAyy
        } else {
            self.rows = [RowsArrayModel]()
        }
    }
}

/**检查列表模型*/
class RowsArrayModel {
    var hospital:String!
    var patientid:String!
    var patientname:String!
    var patientsex:String!
    var patientage:String!
    var patientdob:String!
    var thumbnail:String!
    var studyiuid:String!
    var studyid:String!
    var studydatetime:String!
    var accessionnumber:String!
    var studydesc:String!
    var modality:String!
    var numberofinstances:String!
    var create_datetime:String!
    var reportstatus:String!
    var emergency:String!
    var printed:String!
    var isExt:Bool = false
    var seriesList:[SeriesListArrayModel]?
    
    init(dic:Dictionary<String, AnyObject>) {
        self.rowsArray(dic)
    }
    
    func rowsArray(dic:Dictionary<String, AnyObject>) {
        self.hospital = dic["hospital"] as? String ?? ""
        self.patientid = dic["patientid"] as? String ?? ""
        self.patientname = dic["patientname"] as? String ?? ""
        self.patientsex = dic["patientsex"] as? String ?? ""
        self.patientage = dic["patientage"] as? String ?? ""
        self.patientdob = dic["patientdob"] as? String ?? ""
        self.thumbnail = dic["thumbnail"] as? String ?? ""
        self.studyiuid = dic["studyiuid"] as? String ?? ""
        self.studyid = dic["studyid"] as? String ?? ""
        self.studydatetime = dic["studydatetime"] as? String ?? ""
        self.accessionnumber = dic["accessionnumber"] as? String ?? ""
        self.studydesc = dic["studydesc"] as? String ?? ""
        self.modality = dic["modality"] as? String ?? ""
        self.numberofinstances = dic["numberofinstances"] as? String ?? ""
        self.create_datetime = dic["create_datetime"] as? String ?? ""
        self.reportstatus = dic["reportstatus"] as? String ?? ""
        self.emergency = dic["emergency"] as? String ?? ""
        self.printed = dic["printed"] as? String ?? ""
    }
}

/**检查列表序列模型*/
class SeriesModel {
    var locked:Bool?
}


/**检查列表序列模型*/
class SeriesListArrayModel {
    var seriesiuid:String!
    var seriesnum:String!
    var bodypart:String!
    var seriesdesc:String!
    var numberofinstances:String!
    
    init(dic:Dictionary<String, AnyObject>) {
        self.seriesList(dic)
    }
    
    func seriesList(dic:Dictionary<String, AnyObject>) {
        self.seriesiuid = dic["seriesiuid"] as? String ?? ""
        self.seriesnum = dic["seriesnum"] as? String ?? ""
        self.bodypart = dic["bodypart"] as? String ?? ""
        self.seriesdesc = dic["seriesdesc"] as? String ?? ""
        self.numberofinstances = dic["numberofinstances"] as? String ?? ""
    }
}
let user_serverUrl = "http://dev.yundcm.com"
var user_cookie = "317dd2fd8c991b24235c917ea4949f9b"
var user_uid = "602"
var user_uuid = "269634709c68d9c06d163734e0545ca5"
var user_version = "118"
var user_deviceType = "iPhone%2520Simulator"
class QmAPI {
    var alManager:Manager!
    var alRequst:Request?
    
    init() {
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        config.timeoutIntervalForRequest = 30
        alManager = Manager(configuration: config)
    }
    
    /**登录*/
    func postLogin(username:String, password:String, deviceID:String, deviceType:String, version:String, responseData:(info:Int, message:String) ->Void) {
        if !username.isEmpty && !password.isEmpty {
            
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true

            var pater:[String:AnyObject] = ["device":user_deviceType, "deviceid":user_deviceType, "version":user_version]
            pater["username"] = username
            pater["password"] = password
            pater["clientid"] = "21552"
            alRequst = alManager.request(Method.POST, "\(user_serverUrl)/Mobile/login.ashx", parameters: pater).responseJSON(options: NSJSONReadingOptions.AllowFragments, completionHandler: { (response) in
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                if response.result.isFailure {
                    
                    return
                }
                if let data = response.result.value as? Dictionary<String,AnyObject> {
                    let msg = data["msg"] as? String ?? ""
                    if let status = data["status"] as? String {
                        if status == "success" {
                            if let cookie = data["cookie"] as? String {
                            
                                user_cookie = cookie
                            }
                            
                            if let userID = data["userid"] as? String {
                                user_uid = userID
                            }
                            responseData(info: 1, message: msg)
                        } else if status == "failed" {
                            
                            responseData(info: 4, message: msg)
                        } else {
                            
                            responseData(info: 2, message: msg)
                        }
                    }
                }
            })
        }
        
    }
    
    /**获取检查列表信息*/
    func getStudyQuery(type:String, k:String, d:String, page:Int, rows:Int, sidx:String, sord:String, responseData:(info:Int, message:String, studyMo:StudyGroupModel?) ->Void) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        let pater:[String:AnyObject] = ["type":type, "k":k, "d":d, "page":page, "rows":rows, "sidx":sidx, "sord":sord, "uid":user_uid, "cookie":user_cookie, "deviceid":user_uuid, "device":user_deviceType,"version":user_version, "clientid":user_uuid]
        alRequst = alManager?.request(Method.GET, "\(user_serverUrl)/Mobile/study.ashx", parameters:pater).responseJSON(options: NSJSONReadingOptions.AllowFragments, completionHandler: { (response) -> Void in
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            print(response.request?.URLString)
            if response.result.isFailure {
                print("当前服务器\(user_serverUrl)")
               
                responseData(info: 3, message: "cw", studyMo: nil)
                return
            }
            if let json = response.result.value as? Dictionary<String,AnyObject> {
                let msg = json["msg"] as? String ?? ""
                if let logon = json["logon"] as? Bool {
                    if !logon {
                        responseData(info: 4, message: msg, studyMo: nil)
                        return
                    }
                }
                if let status = json["status"] as? String {
                    if status == "success" {
                        let studyMo = StudyGroupModel(dic: json)
                        if studyMo.records > 0 {
                            if studyMo.rows.count > 0 {
                                responseData(info: 1, message: "请求成功", studyMo: studyMo)
                            } else if studyMo.total < studyMo.page && studyMo.total > 0 {
                                responseData(info: 6, message: "没有更多检查记录了", studyMo: nil)
                            } else {
                               
                                responseData(info: 5, message: "没有查询到检查记录", studyMo: nil)
                            }
                        } else {
                            responseData(info: 0, message: "没有查询到检查记录", studyMo: nil)
                        }
                    } else if let msg = json["msg"] as? String {
                        
                        responseData(info: 2, message: msg, studyMo: nil)
                    } else {
                        
                        responseData(info: 2, message: msg, studyMo: nil)
                    }
                } else {
                    
                    responseData(info: 2, message: msg, studyMo: nil)
                }
            } else {
               
                responseData(info: 2, message: "", studyMo: nil)
            }
        })
    }
    
    //http://cq.pacs120.com/mobile/SeriesQuery.ashx?patientID=93132190&StudyUID=1.2.840.78.75.7.5.881.1439861174&uid=15&cookie=7Wv0e/A28SQH5332izBR6DrxP5GJ5AZMiehay17ODTM=&deviceid=dbd19f1b77ef9e75&version=1.2.0
    /**获取检查列表二级信息*/
    func getSeriesQuery(patientid:String, studyiuid:String,responseData:(info:Int, message:String, seriesrray:[SeriesListArrayModel]) ->Void) {
        var pater:[String:AnyObject] = ["uid":user_uid, "cookie":user_cookie, "device":user_deviceType, "deviceid":user_uuid, "version":user_version]
        pater["patientid"] = patientid
        pater["studyiuid"] = studyiuid
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        alRequst = alManager.request(Method.GET, "\(user_serverUrl)/Mobile/series.ashx", parameters: pater).responseJSON(options: NSJSONReadingOptions.AllowFragments, completionHandler: { (response) in
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            if response.result.isFailure {
                responseData(info: 2, message: "xx", seriesrray: [])
                return
            }
            if let json = response.result.value as? Dictionary<String,AnyObject> {
                let msg = json["msg"] as? String ?? ""
                if let logon = json["logon"] as? Bool {
                    if !logon {
                        responseData(info: 4, message: msg, seriesrray: [])
                        return
                    }
                }
                let status = json["status"] as? String ?? ""
                if status == "success" {
                    if let seriesAy = json["rows"] as? [Dictionary<String, AnyObject>] {
                        var serArray = [SeriesListArrayModel]()
                        for series in seriesAy {
                            let serMo = SeriesListArrayModel(dic: series)
                            serArray.append(serMo)
                        }
                        
                        responseData(info: 1, message: "成功", seriesrray: serArray)
                    } else {
                        
                        responseData(info: 2, message: status, seriesrray: [])
                    }
                } else if status == "failed" {
                    
                } else {
                    
                    responseData(info: 2, message: status, seriesrray: [])
                }
            } else {
            }
        })
    }
}